﻿using JobSchedule.Base;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Configuration;

namespace JobSchedule.Jobs
{
    public class EdsResetJob : JobBase
    {
        /// <summary>
        /// 检测eds宕机，重启iis
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteJob(IJobExecutionContext context)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
            //判断网页是否正常
            var url = ConfigurationManager.AppSettings["edsurl"];
            var timeout = ConfigurationManager.AppSettings["edstimeout"];
            try
            {
                var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";
                req.Timeout = int.Parse(timeout);
                using (var res = (HttpWebResponse)req.GetResponse())
                {
                    var StatusCode = res.StatusCode.ToString();
                    Console.WriteLine(StatusCode);
                }
            }
            catch (WebException ex)
            {
                //重启IIS
                var strOuput = IISResetProcess();
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Out.WriteLineAsync("EDS宕机了>>>>>>>" + ex.ToString() + "\r\n重启iis>>>>>>>" + strOuput);
                logger.Error("EDS宕机了,IIS已自动重启！ >>>>>>>" + ex.ToString() + "\r\n重启iis>>>>>>>" + strOuput);
            }
        }

        public string IISResetProcess()
        {
            Process pro = new Process();
            // 设置命令行、参数
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.CreateNoWindow = true;
            // 启动CMD
            pro.Start();
            // 运行端口检查命令
            //pro.StandardInput.WriteLine("iisreset");
            //通过psexec远程执行命令
            pro.StandardInput.WriteLine(@"cd /d D:\RestartEdsJob\PSTools");
            pro.StandardInput.WriteLine(@"psexec \\192.168.10.1 -u sqauser -p EDS@NewTouch% -d -s iisreset /restart");
            pro.StandardInput.WriteLine("exit");
            return pro.StandardOutput.ReadToEnd();
        }

    }
}
